import * as vscode from 'vscode';
import * as util from '../util/util';
import * as logic from '../logic/logic';
import * as languageOutput from '../languageOutPut/languageOutput';
import { handleTplFn } from './handleTpl';
import { _global } from '../util/CONST';


//在对应文件头部添加头部注释
export function headerAnnotation(editor: vscode.TextEditor | undefined, option: any = {}) {
    if(!editor) { return };
    const config = vscode.workspace.getConfiguration('fileheader'); //配置项默认值
    console.log('config', config);
    //默认合并
    editor.edit(async (editBuilder: vscode.TextEditorEdit) => {
        try {
            //文件后缀
            let fileEnd = editor.document.languageId; //语言
            console.log('语言', fileEnd);
            fileEnd = util.fileEndMatch(fileEnd) //提取文件后缀 或者语言类型
            console.log('提取文件后缀 或者语言类型', fileEnd, option.create);
            if (option.create && fileEnd == _global.NoMatchLanguage) return; // 创建文件匹配不到_默认注释 不自动添加头部注释
            //返回生成模版的数据对象
            const data = logic.userSet(config);
            console.log('返回生成模版的数据对象\n', data);
            // 生成
            const tpl = languageOutput.headNotes(data, fileEnd, config);
            console.log("生成tpl\n", tpl);
            // 处理生成的模板
            const { lineNum, newTpl } = handleTplFn(
                tpl,
                editor.document.uri.fsPath,
                config,
                fileEnd
            )
            console.log("处理生成的模板\n", newTpl);
            console.log("插入到第" + lineNum + "行");
            editBuilder.insert(new vscode.Position(lineNum, 0), newTpl) //插入
            setTimeout(async () => {
                await editor.document.save();
                logic.moveCursor(newTpl)
             }, 100);
        } catch (error) {

        }
    })
}